<template>
  <div class="m_right">
    <p></p>
    <div class="mem_tit">分类列表</div>
    <div style="text-align:center">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" size="mini">
        <el-form-item label="分类名称">
          <el-input v-model="searchForm.name" placeholder="输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="分类级别">
          <el-select v-model="searchForm.type" placeholder="选择分类级别">
            <el-option label="所有级别" value=""></el-option>
            <el-option label="一级分类" value="1"></el-option>
            <el-option label="二级分类" value="2"></el-option>
            <el-option label="三级分类" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain size="mini" @click="addCategoryClick">新增分类</el-button>
        </el-form-item>

      </el-form>
      
      <!-- 新增-对话框 -->
      <el-dialog title="新增列表" :visible.sync="addCategoryViewShow">
        <el-form :model="categoryForm" label-width="240px" inline>
          <el-form-item label="一级分类：" v-if='categoryForm.type == 1' style="margin-left: 0px;padding-left:0px">
            <el-input v-model="categoryForm.firstCategoryName" placeholder="输入一级分类名称"></el-input>
          </el-form-item>
          <el-form-item>
            <a class="el-icon-circle-plus-outline" @click='showFirstCategoryList' v-if='categoryForm.type == 1' href="javascript:;">新增二级分类</a>
          </el-form-item>


          <el-form-item label="一级分类：" v-if='categoryForm.type &gt;= 2'>
            <el-select v-model="categoryForm.firstCategoryId" @change="changeFirstCategoryId">
              <el-option v-for="category in categoryForm.firstCategoryList" :label="category.name" :value="category.id" :key="category.id"></el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="二级分类：" v-if='categoryForm.type == 2'>
            <el-input v-model="categoryForm.secondCategoryName" placeholder="输入二级分类名称"></el-input>
          </el-form-item>

          <el-form-item>
            <a class="el-icon-circle-close" @click='upShowFirstCategoryList' v-if='categoryForm.type == 2' href="javascript:;">取消二级分类</a>&nbsp;&nbsp;
            <a class="el-icon-circle-plus-outline" @click='showSecondCategoryList' v-if='categoryForm.type == 2' href="javascript:;">新增三级分类</a> 
          </el-form-item>

          <el-form-item label="二级分类：" v-if='categoryForm.type == 3'>
            <el-select v-model="categoryForm.secondCategoryId">
              <el-option v-for="category in categoryForm.secondCategoryList" :label="category.name" :value="category.id" :key="category.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="三级分类：" v-if='categoryForm.type == 3'>
            <el-input v-model="categoryForm.thirdCategoryName" placeholder="输入三级分类名称"></el-input>
          </el-form-item>

          <el-form-item>
            <a class="el-icon-circle-close" @click='upShowSecondCategoryList' v-if='categoryForm.type == 3' href="javascript:;">取消三级分类</a> 
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelSubmit">取 消</el-button>
          <el-button type="primary" @click="addSubmit">新 增</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 表格展示 -->
    <el-table
      v-loading="loading"
      element-loading-spinner="el-icon-loading"
      :data="categoryList"
      style="width: 90%"
    >
      <el-table-column label="分类名称" header-align="center" align="center">
        <template slot-scope="scope">
          <a href="javascript:;">{{ scope.row.name }}</a>
        </template>
      </el-table-column>
      <el-table-column label="分类级别" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ calculateType(scope.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="父级分类"
        header-align="center"
        align="center"
        min-width="80px"
      >
        <template slot-scope="scope">
          <span>{{ categoryObj[scope.row.parentId] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        header-align="center"
        align="center"
        width="180px"
      >
        <template slot-scope="scope">
          <!-- 这里直接在修改按钮绑定原生bom点击事件，展示modifyDialog同时展示传入id，直接在data中的newsList数组中查询到该资讯，免去服务端查询-->
          <el-button
            type="info"
            size="mini"
            @click.native="categoryModifyOrShow(scope.row.id)"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="mini"
            @click="deleteCategory(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改对话框 -->
    <el-dialog title="修改分类" :visible.sync="modifyDialog">
      <el-form v-if="modifyCategory && categoryList">
        <el-form-item label="当前分类: " label-width="30%">
          <span style="color:green;">{{calculateCategory(modifyCategory.parentId)}}</span>
        </el-form-item>
        <el-form-item label="分类名称: " label-width="30%">
          <el-input v-model="modifyCategory.name"></el-input>
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyDialog = false">取 消</el-button>
        <el-button type="primary" @click="modifySubmit()">确 定</el-button>
      </div>
    </el-dialog>
    

    <br />
    <!-- 分页 -->
    <div class="page">
      <el-pagination
        prev-text="上一页"
        next-text="下一页"
        background
        @current-change="handleCurrentChange"
        :page-size="pageInfo.pageSize"
        :current-page="1"
        layout="prev, pager, next, jumper"
        :total="pageInfo.total"
        ><!-- 注意这里pageInfo.total是来自pageHelper的pageinfo，而不是自己封装的pageinfo -->
      </el-pagination>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import {
  Table,
  TableColumn,
  Loading,
  Button,
  Dialog,
  Pagination,
  Form,
  FormItem,
  Input,
  Select,
  Option,
} from "element-ui";
Vue.use(Table);
Vue.use(TableColumn);
Vue.use(Dialog);
Vue.use(Button);
Vue.use(Pagination);
Vue.use(Form);
Vue.use(FormItem);
Vue.use(Input);
Vue.use(Select);
Vue.use(Option);
Vue.use(Loading.directive);
export default {
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      pageInfo: {},
      searchForm: {
        name: null,
        type: ''
      },
      loading: false, // 新增 loading 状态
      categoryList: [],
      addCategoryViewShow: false, //展示新增分类对话框
      categoryObj: {}, //展示所有分类的key: id value: name之间对应关系
      categoryForm: { //分类一般不会很多，直接读取到前端
        type: 1, 
        firstCategoryName: '',
        firstCategoryId: '',
        firstCategoryList: [],
        secondCategoryName: '',
        secondCategoryId: '',
        secondCategoryList: [], //二级分类基于一级分类
        thirdCategoryName: '', //三级分类就是最后一级了，对于添加不需要下拉框，
      },
      //修改相关
      modifyDialog: false,
      modifyCategory: null,
      oldCategoryName: '',
      allCategoryList: [],

    };
  },
  methods: {
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getCategoryList();
    },
    getCategoryList() {
      this.loading = true; // 开始加载时显示 loading
      this.$axios({
        url: "/api/category/pageinfo",
        method: "POST",
        data: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.searchForm.name,
          type: this.searchForm.type
        },
      })
        .then((rs) => {
          this.categoryList = rs.data.pageinfo.list;
          this.pageInfo = rs.data.pageinfo;
          this.pageNum = this.pageInfo.pageNum;
        })
        .finally(() => {
          this.loading = false; // 加载完成后隐藏 loading
        });
    },
    getAllCategory() {
      this.$axios({
        url: "/api/category/all",
        method: "POST",
      }).then((rs) => {
        this.categoryObj[0] = "无";
        rs.data.categories.forEach((i) => {
          this.categoryObj[i.id] = i.name;
        });
        this.allCategoryList = rs.data.categories;
      });
    },
    calculateType(type) {
      return type == 1 ? "一级分类" : type == 2 ? "二级分类" : "三级分类";
    },
    searchSubmit() {
      this.getCategoryList();
    },
    addCategoryClick() {
      //前置操作
      this.categoryForm.type = 1;
      this.categoryForm.firstCategoryName = '';
      this.categoryForm.firstCategoryId = ''
      this.categoryForm.secondCategoryId = '';
      this.categoryForm.secondCategoryName = ''
      this.categoryForm.thirdCategoryName = '';
      this.addCategoryViewShow = true
    },
    //展示一级分类列表
    showFirstCategoryList() {
      this.categoryForm.type = 2;
     
        this.$axios({
        url: "/api/category/first",
        method: "POST",
      })
        .then(rs => {
          console.log("获取一级分类", rs);
          //符合条件才进入二级分类输入
          if(rs.data.categories.length <= 0) {
            this.$message.error("至少添加一个一级分类才能新增二级分类");
            return;
          }
          this.categoryForm.firstCategoryList = rs.data.categories;
        })
      
      // this.categoryForm.firstCategoryId = this.categoryForm.firstCategoryList[0].id;
    },
    showSecondCategoryList() {
      this.categoryForm.secondCategoryId = this.categoryForm.firstCategoryList[0].id //保证二级分类一定是一级的子类
      if(!this.categoryForm.firstCategoryId) {
        this.$message.error("请选择一个一级分类");
        return;
      }
      this.$axios({
        url: "/api/category/second",
        method: "POST",
        data: {
          id: this.categoryForm.firstCategoryId
        }
      })
        .then(rs => {
          console.log("获取二级分类", rs);
          if(rs.data.categories.length == 0) {
            this.$message.error("当前一级分类下没有二级分类，请至少创建一个二级分类");
            return;
          }
          this.categoryForm.type = 3; //符合条件才展示
          this.categoryForm.secondCategoryList = rs.data.categories;
        })
      this.categoryForm.secondCategoryId = this.categoryForm.secondCategoryList[0].id
    },
    changeFirstCategoryId() { //当一级分类变化时，根据数据动态是否展示二级甚至三级
      this.$axios({
        url: "/api/category/second",
        method: "POST",
        data: {
          id: this.categoryForm.firstCategoryId
        } 
      })
        .then(rs => {
          console.log("获取二级分类", rs);
          if(rs.data.categories.length == 0) {
            if(this.categoryForm.type == 3) {
              this.categoryForm.type = 2;
              this.categoryForm.secondCategoryName = '';
              this.categoryForm.thirdCategoryName = ''
            }
            this.$message.error("当前一级分类下没有二级分类，请至少创建一个二级分类");
            return;
          }
          if(this.categoryForm.type == 3)
          this.categoryForm.type = 3; //符合条件才展示
          this.categoryForm.secondCategoryId = rs.data.categories[0].id;
          this.categoryForm.secondCategoryList = rs.data.categories;
        })
      this.categoryForm.secondCategoryId = this.categoryForm.secondCategoryList[0].id
    },
    addSubmit() {
      //判断元素是否正确
      if(this.categoryForm.type == 1 && !this.categoryForm.firstCategoryName) {
        this.$message.error("一级分类输入不能为空");
          return;
      }
      if(this.categoryForm.type == 2) {
        if(!this.categoryForm.firstCategoryId) {
          this.$message.error("请选择一个一级分类");
          return;
        }
        if(!this.categoryForm.secondCategoryName) {
          this.$message.error("二级分类输入不能为空");
          return;
        }
      }
      if(this.categoryForm.type == 3) {
        if(!this.categoryForm.secondCategoryId) {
          this.$message.error("请选择一个二级分类");
          return;
        }
        if(!this.categoryForm.thirdCategoryName) {
          this.$message.error("三级分类输入不能为空");
          return;
        }
      }
      //
      this.$axios({
        url: '/api/category/add',
        method: 'POST',
        data: {
          type: this.categoryForm.type,
          name: this.categoryForm.type == 1 ? this.categoryForm.firstCategoryName : (this.categoryForm.type == 2 ? this.categoryForm.secondCategoryName : this.categoryForm.thirdCategoryName),
          parentId: this.categoryForm.type == 1 ? 0 : (this.categoryForm.type == 2 ? this.categoryForm.firstCategoryId : this.categoryForm.secondCategoryId),
        }
      }).then(rs => {
        if(rs.data.code == 5200) {
          this.addCategoryViewShow = false;
          this.getAllCategory();
          this.getCategoryList();
          //清除sessionStorage，因为之前缓存了相关数据
          sessionStorage.removeItem("firstLevelList")
          sessionStorage.removeItem("levelMap")
          this.$message.success(rs.data.msg);
        }else {
          this.$message.error(rs.data.msg);
        }
      })
    },
    upShowFirstCategoryList() { //取消二级分类，即不展示一级分类列表，直接展示一级分类输入框
      this.categoryForm.type = 1;
      //数据还原，不能下次展示时输入框里面就有值
      this.categoryForm.secondCategoryName = ''
    },
    upShowSecondCategoryList() {
      this.categoryForm.type = 2
      this.categoryForm.thirdCategoryName = ''
    },
    cancelSubmit() {
      this.addCategoryViewShow = false;
      this.categoryForm.type = 1
      this.categoryForm.firstCategoryId = ''
      this.categoryForm.firstCategoryName = ''
    },


    //---------------------修改-------------------------
    calculateCategory(parentId) { //计算分类名展示
      console.log("parentId: " + parentId)
        let pId = parentId;
        let name = ``;
        if(pId == 0) return "全部 ->"
        //跟着parentId找，最多找两次
        this.allCategoryList.forEach(i => {
          if(i.id == pId) {
            name = i.name
            pId = i.parentId;
          }
        })
        if(pId == 0) return "全部 ->" + name;
        this.allCategoryList.forEach(i => {
          if(i.id == pId) {
            name = i.name + ' - ' + name; 
            
          }
        })
        return "全部 -> " + name; 
    },

    categoryModifyOrShow(id) {
      this.modifyDialog = true;
      this.categoryList.forEach(i => {
        if(i.id == id) this.modifyCategory = i;
      })
      this.oldCategoryName = this.modifyCategory.name;
    },
    modifySubmit() {
      if(this.oldCategoryName == this.modifyCategory.name) {
        this.$message.warning("分类尚未改动！");
        return;
      }
      this.$axios({
        url: '/api/category/update',
        method: 'post',
        data: this.modifyCategory
      }).then(rs => {
        console.log("修改结果： ", rs);
        if(rs.data.code == 5200) {
          this.modifyCategory = {};
          this.$message.success('修改');
          window.location.reload();
        }else {
          this.$message.error(rs.data.msg);
        }
      })
      // modifyDialog = false;
    },

    // -------------------删除-------------------------
    deleteCategory(id) {
      // console.log(id);
      this.$messageBox.confirm("是否要删除该分类？", "提示", {  
        confirmButtonText: '确定',  
        cancelButtonText: '取消',  
        type: 'warning'  
      }).then(() => {  
        // 用户点击了确定，执行删除操作  
        this.$axios({  
          url: '/api/category/delete',  
          method: 'post',  
          data: { id: id }  
        }).then(rs => {  
          if (rs.data.code === 5200) {  
            this.$message.success('商品删除成功！');  
            //清除sessionStorage，因为之前缓存了相关数据
            sessionStorage.removeItem("firstLevelList")
            sessionStorage.removeItem("levelMap")
            window.location.reload(); // 关键点！
          } else {
            this.$message.error(rs.data.msg);
          }
        }).catch(error => {  
          console.error('删除失败:', error);  
          this.$message.error(error);  
        });  
      }).catch(() => {  
        // 用户点 击了取消，不执行任何操作  
        this.$message.info('已取消删除');  
      });  
    }


  },

  created() {
    this.getAllCategory();
    this.getCategoryList();
  },
};
</script>

<style>
.page {
  width: 100%;
  padding: 2rem;
  text-align: center;
}
</style>